package com.krt.facenettydemo.netty;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.krt.facenettydemo.NettyBean;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;


/**
 * @author Marcus
 * @package krt.wid.tour_gz.net.netty
 * @description
 * @time 2018/12/4
 */
public class NettyHandler extends ChannelHandlerAdapter {
    private final String TAG = "NettyHandler";

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        JSONObject jsonObject = new JSONObject((String) msg);
        if (jsonObject.has("heart_beat")) {
            Log.w("marcus", "心跳包:" + msg);
        } else {
            EventBus.getDefault().post(msg);
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
        if (!TextUtils.isEmpty(keepJson())) {
            Log.w("marcus", "保持心跳:" + keepJson());
            ctx.writeAndFlush(keepJson());
        }

    }

    public String keepJson() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("heart_beat", "1");
            return jsonObject.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return ":";
    }
}
